var WASP_PRD_TEMPLATE = {
	fileUploadTypes: function() {
		var serviceType = $("#serviceType").val();
		var todoType = $("#todoType").val();
		var fileTypes = uploadFileTypeMap[serviceType + '_' + todoType];
		return fileTypes;
	},
		
	submitAddForm : function(confirmResult) {
		SubmitAndPreventSecond("addForm",function(){
			// 确认材料时，若操作为驳回，则需要填写审批意见
			if (operType == 'fileConfirm' && confirmResult == 'R') {
				$("#opinion").rules("add", {
					required : true, messages:{required:"请填写审批意见"}
				});
			} else {
				$("#opinion").rules("remove");
			}
			
			if(!$("#addForm").valid()) {
				toastr.warning('', '请完善信息');
				return false;
			}
			if(confirmResult == 'S') {  // 上传附件
				var flag = true;
				var archiveInfoJson = [];
				// 材料附件ID
				var attachIds = $("#attachContainertodoAddView input[name='attId']");
				// 上传材料时，要求必须上传
				if (operType == 'fileUpload' && attachIds.length == 0) {
					ctools.alert("请上传材料", "", "warning");
					return false;
				}
				

				
				attachIds.each(function() {
					var attachRelObject = {};
					var attachId = $(this).val();
					var extId = $("#fileTypeExtId"+attachId).val();
					var expandField = "fileType" + attachId;
					var expandValue = $("#" + expandField).val();
					
					var fileUploadTypes = WASP_PRD_TEMPLATE.fileUploadTypes();
					if (!expandValue && fileUploadTypes && fileUploadTypes.length > 0) {
						ctools.alert("请选择材料类型", "", "warning");
						flag = false;
						return false;
					}
					attachRelObject.attachId = attachId;
					attachRelObject.expandField = "fileType";
					attachRelObject.expandValue = expandValue;
					attachRelObject.relType = "MY_TODO";
					// extId为空
					if(extId){
						attachRelObject.extId = extId;
					}
					archiveInfoJson.push(attachRelObject);
				});
				
				if(!flag) {
					return false;
				}
				$("#attachJson").val(JSON.stringify(archiveInfoJson));
			}
			
			$("#confirmResult").val(confirmResult);
			
			// 产出物附件id
			var e_moduleValue = $("#attIdstodoFileEndView").val();
			$("#fileEndAttId").val(e_moduleValue);
			
			
			// 完成时，要求产出物必须上传
			if ((confirmResult == 'E' || confirmResult == 'E_TEMP') && !e_moduleValue) {
				ctools.alert("请上传产出报告或文件", "", "warning");
				return false;
			}
			
			return true;
		}, true);
	},
		
	initJqValidate: function() {

		$("#addForm").validate({
			focusCleanup : true,
			ignore: ":hidden",
			rules : {
				manageCompany : {
					required : true
				},
				serviceType: {
					required : true
				},
				todoType : {
					required : true
				},
				todoDate : {
					required : true
				},
				noFile : {
					required : true
				},
				prjCode: {
					required: true
				}
			},
			messages : {
				manageCompany : {
				  required:'请选择管理人'
		        },
		        serviceType : {
		        	required : '请选择服务类型'
		        },
		        todoType : {
				  required : '请选择待办类型'
				},
				todoDate : {
				  required : '请选择待办日期'
				},
				noFile : {
					required : '请确认是否无材料上传'
				},
				prjCode: {
					required: '请选择产品'
				}
			}
		});
	}
};


$(function() {
	if (operType == 'add') {
		initLinkendDate();
		initFileTypes();
	} else {
		initFileTypes();
		showUploadTips();
	}
	
	// 初始化校验
	WASP_PRD_TEMPLATE.initJqValidate();
	// select2控件初始化
	$(".select2").select2();
	// select2 change自动校验
	$("select").change( function() {
		var $this=$(this);
		$this.valid && $this.valid();
	});
	
	WASP_WIDGET.triggerIRadio("input[name=noFile]");
	
	// 管理人初始化
	WASP_WIDGET.triggerCompanySelect("#manageCompany");
	
	// 待办日期
	WASP_WIDGET.triggerDateStyleWithYMD("#todoDate");
	$("#todoDate").on("change", function(){
		$(this).valid && $(this).valid();
	});
	
	
//	if($("#attIdsInput").length != 0) {
		var attIds = $("#attIdsInput").val();
		if(attIds.length == 0) {
		} else {
			$("#attIdsInput").val(attIds + "," + f.id);
		}
		
		var attids = '';
		$("#attachContainertodoAddView input[name='attId']").each(function() {
			if(attIds.length == 0) {
				$("#attIdsInput").val($(this).val());
			} else {
				$("#attIdsInput").val(attIds + "," + $(this).val());
			}
		});
		uploadFileCustom();
		deleteInputAttachFile();
//	}
	
});


var todoTypeMap = {};
var uploadFileTypeMap = {};
function initLinkendDate() {
	//准备联动数据 待办类型与上传材料提示文字
	for (var i = 0; i < todoTypes.length; i++) {
		var todoType = todoTypes[i];
		if (!todoTypeMap[todoType.dctLeftType]) {
			todoTypeMap[todoType.dctLeftType] = [];
		}
		todoTypeMap[todoType.dctLeftType].push(todoType);
	}
}

function initFileTypes() {
	if (window.fileType2JsonObj) {
		for (var i = 0; i < fileType2JsonObj.length; i++) {
			var fileType = fileType2JsonObj[i];
			
			if (!uploadFileTypeMap[fileType.dctFathType + '_' + fileType.dctLeftType]) {
				uploadFileTypeMap[fileType.dctFathType + '_' + fileType.dctLeftType] = [];
			}
			uploadFileTypeMap[fileType.dctFathType + '_' + fileType.dctLeftType].push(fileType);
		}
	}
}


function changeServiceType() {
	var serviceType = $("#serviceType").val();
	$("#todoType").html('');
	$("#todoType").append('<option value=""></option>');
	if (serviceType) {
		var todoTypes = todoTypeMap[serviceType];
		if (todoTypes && todoTypes.length) {
			$.each(todoTypes, function(i, todoType){
				$("#todoType").append('<option value="' + todoType.dctValue + '">' + todoType.dctName + '</option>');
			});
		}
		
		$("#todoType").trigger('change');
	}
	
	showUploadTips();
	
	if (serviceType == 'INFO_DIS_REGULATORY') {
		$("#prjCodeContainer").hide();
	} else {
		$("#prjCodeContainer").show();
	}
}

function changeTodoType() {
	showUploadTips();
}


function showUploadTips(serviceType, todoType) {
	$("#uploadTips").hide();
	$("#needUploadFileTyps").html('');
	var serviceType = $("#serviceType").val();
	var todoType = $("#todoType").val();
	if (!serviceType || !todoType) {
		return;
	}
	
	var fileTypes = uploadFileTypeMap[serviceType + "_" + todoType];
	var fileTypesOption = [];
	if (fileTypes && fileTypes.length) {
		$.each(fileTypes, function(i, fileType){
			$("#needUploadFileTyps").append('<span class="fileTip">' + (i+1) + '.' + fileType.dctName + '</span>');
			
			fileTypesOption.push('<option value="' + fileType.dctValue + '">' + fileType.dctName + '</option>');
		});
		$("#uploadTips").show();
	}

	$("select[class*=fileTypeSelect]").html('');
	$("select[class*=fileTypeSelect]").append('<option><option>');
	$("select[class*=fileTypeSelect]").append(fileTypesOption.join(""));
	
	// 编辑时回显数据库值
	var $fileTypes = $(".fileTypeSelect");
	$.each($fileTypes, function(i, fileType) {
		var initValue = $(fileType).data("init-value");
		$(fileType).val(initValue);
	});
	$("select[class*=fileTypeSelect]").trigger("change");
	
	fileType2Json = fileTypesOption.join();
	
	// 对于已上传的文件，添加材料类型的下拉框选项
	if (fileType2Json && fileType2Json != "") {
		var $fileTypeTd = $("td[class='fileTypeSelect']");
		$.each($fileTypeTd, function(i, fileTypeTd) {
			var fileId = $(fileTypeTd).parent().attr("id");
			var selectDom = $('<select class="select2 fileTypeSelect" id="fileType' + fileId + '"><option></option>' + fileType2Json + '</select>');
			$(fileTypeTd).append(selectDom);
			
			selectDom.select2();
		});
	} else {
		// 隐藏材料类型下拉框
		$("select[class*=fileTypeSelect]").remove();
	}
	
}

function uploadFileCustom() {
	$("#uploadBtnCustom").upload({
		url : '/scbp/sys/attach/uploadFile4Create.do',
		container : '#attachContainertodoAddView',
		// 可见最大可上传大小，可选
		size : 31457280,
	    //是否多文件上传
        multiple: true,
		//可选参数
        data: {resourceSign : "MY_TODO"},
        //文件类型
        type: null,
        typeMessage: null,
        //上传失败
        loadingPreview: function(f) {
        	
        	var arr = [];
        	arr.push("<tr style='background-color:#FFFFCC'>");
        	arr.push('<td><a style="color:#000000;text-decoration:underline;" href="/solution/sys/attach/downloadAttach.do?attId=1056" target="_blank" name="attName">' + f.name + '</a></td>');
        	arr.push("<td></td>");
        	arr.push("<td></td>");
        	arr.push('<td>正在上传...<span class="f-progress">0</span>%</td>');
        	arr.push("<td>" + current_name + "</td>");
        	arr.push("<td>" + dateFormat() + "</td>");
        	arr.push("<td><a href='javascript:void(0)' title='取消上传' class='btn btn-link btn-jqgrid f-cancel'><i class='fa fa-reply'></a></td>");
        	arr.push("</tr>");
        	
        	
        	return arr.join('');
        },
        donePreview: function(f) {
        	if (f.isOK == 'success') {
        		var attIds = $("#attIdsInput").val();
        		if(attIds.length == 0) {
        			$("#attIdsInput").val(f.id);
        		} else {
        			$("#attIdsInput").val(attIds + "," + f.id);
        		}
        		
        		var arr = [];
            	arr.push('<tr class="uploaded" id="' + f.id + '">');
            	arr.push('<input type="hidden" name="attId" value="' + f.id + '">');
            	arr.push('<td><a style="color:#000000;text-decoration:underline;" href="/solution/sys/attach/downloadAttach.do?attId=' + f.id + '" target="_blank" name="attName">' + f.name + '</a></td>');
            	arr.push("<td>" + f.resourceSignName + "</td>");
            	
            	// 未配置材料类型的，无需选择材料类型
            	var fileUploadTypes = WASP_PRD_TEMPLATE.fileUploadTypes();
            	if (fileUploadTypes && fileUploadTypes.length > 0) {
            		arr.push('<td class="fileTypeSelect">' + '<select class="select2 fileTypeSelect" id="fileType' + f.id + '"><option></option>' + fileType2Json + '</select>' + '</td>');
            	} else {
            		arr.push('<td class="fileTypeSelect"></td>');
            	}
            	arr.push('<td>已上传</td>');
            	arr.push("<td>" + current_name + "</td>");
            	arr.push("<td>" + dateFormat() + "</td>");
            	arr.push('<td><a style="display:inline;" href="#" title="删除附件" class="btn btn-link btn-jqgrid f-delete" data-toggle="modal" data-target="#modal-info" name="attDelBtn">删除</a></td>');
            	arr.push("</tr>");
            	
            	return arr.join('');
        		
        	} else {
        		ctools.alert("文件上传失败", f.errorMessage, "error");
        	}
        },
        failPreview: function(f) {
        	ctools.alert("文件上传失败", f.errorMessage, "error");
        },
        doneCall: function (result){
        	$('#fileType' + result.id).select2({placeholder: "材料类型"});
        	deleteInputAttachFile();
        },
		showError : function(e) {
			ctools.alert("文件上传失败", e.msg,"error");
		}
	});
}

/**
 * 附件文件删除，并移除显示
 */
function deleteInputAttachFile(){
	//删除上传成功附件
	$('#attachContainertodoAddView').on('click', '.uploaded .f-delete', function() {
		var $tr = $(this).parents('tr[class*=uploaded]');
	    var	attachId = $tr.attr("id");
		ctools.confirm({
			title : "确认删除附件？",
			text : ""
		}, function(isConfirm) {
			if (isConfirm) {
				if (attachId != undefined || attachId != null){
					$.ajax({
						type : "GET",
						cache : false,
						ifModified : true,
						dataType : "json",
						url : '/solution/sys/attach/delAttachInfo.do?attId=' + attachId,
						success : function(data) {
							if('1' == data.state){
								ctools.alert_sweet('删除失败！','error',data.stateMsg);
							}else{
								if('1' == data.isOK){
									ctools.alert_sweet("删除附件成功！", 'success', '');
									
									var attIds = $("#attIdsInput").val();
									var index = attIds.indexOf(attachId);
									var subStr = attIds;
									//当前仅上传了一个文件
									if(attIds.indexOf(",") < 0){
										subStr = attIds.replace(attachId, "");
									}else{
										if(index == 0){
											subStr = attIds.replace(attachId + ",", "");
										}else if(index > 0){
											subStr = attIds.replace("," + attachId, "");
										}else{
											//改附件不属于当前上传的附件，不作处理
										}
									}
									$("#attIdsInput").val(subStr);
									
									
									$tr.remove();
								} else{
									ctools.alert_sweet("删除附件失败！", 'error',  data.msg);
								}
							}
						},
						error : function(jqXHR, textStatus, errorThrown) {
							ctools.alert_sweet("删除附件数据错误！", 'error', textStatus);
						}
					});
				}
			}
		});
	});
	//删除上传失败附件
	$('#attachContainertodoAddView').on('click', '.upload-error .f-delete', function() {
		$(this).parents('tr[class*=upload-error]').remove();
	});
}

// 变更管理人时，初始化产品下拉框，只能选择对应管理人下的产品
function changeManageCompany() {
	// 清空已选产品
	$("#prjCode").val("").trigger("change");
	var manageCompany = $("#manageCompany").val();
	if (manageCompany) {
		WASP_WIDGET.triggerPrdInfoSelect("prjCode", {manageCompany: manageCompany});
	} else {
		$("#prjCode").select2();
	}
}


